﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel.DataAnnotations;
using System.Globalization;

namespace PilotProject.Validation
{
    public class ValidGuidAttribute : ValidationAttribute
    {


        public ValidGuidAttribute()
            : base(){ }

        public ValidGuidAttribute(string message)
            : base(message) { }

        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            var input = Convert.ToString(value, CultureInfo.CurrentCulture);

            // let the Required attribute take care of this validation 
            if (string.IsNullOrWhiteSpace(input))
            {
                return null;
            }

            


            Guid guid;
            if (!Guid.TryParse(input, out guid))
            {

                
                // not a validstring representation of a guid 
                return new ValidationResult(FormatErrorMessage(validationContext.DisplayName));
            }
            else
            {
                if (guid.Equals(Guid.Empty))
                {
                    return new ValidationResult(FormatErrorMessage(validationContext.DisplayName));
                }

                return null;
            }


        }
    }
}
